/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.zhpan.bannerview;

import ohos.agp.components.AttrHelper;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;
import ohos.agp.components.StackLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;

import com.youth.banner.ResourceTable;
import com.zhpan.bannerview.listener.OnBannerClickListener;
import com.zhpan.bannerview.listener.OnBannerListener;
import com.zhpan.bannerview.loader.ImageLoaderInterface;
import com.zhpan.bannerview.options.Options;
import com.zhpan.bannerview.view.BannerViewPager;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;
import static ohos.multimodalinput.event.TouchEvent.CANCEL;
import static ohos.multimodalinput.event.TouchEvent.NONE;
import static ohos.multimodalinput.event.TouchEvent.PRIMARY_POINT_DOWN;
import static ohos.multimodalinput.event.TouchEvent.PRIMARY_POINT_UP;

/**
 * Banner1
 *
 * @since 2021-03-24
 */
public class Banner1 extends StackLayout implements PageSlider.PageChangedListener {
    private static final int ONE = -1;
    private static final int THREE = 3;
    private static final int FIVETY = 50;
    private static final int SIXTEEN = 16;
    private static final float ONEFOUR = 1.4f;
    private static final int NINE = 9;
    private static final float ZEROFIVE = 0.5F;
    private static final int TWO = 2;
    private static final int FOUR = 4;
    private static final int FIVE = 5;
    private static final int SIX = 6;
    private static final int SEVEN = 7;
    private static final int EIGHT = 8;
    private static final int TEN = 10;
    private static final int THREEZERO = 30;
    private static final int EIGHTONE = 81;
    private static final int TWOTY = 20;
    private static final int ONEZEROZERO = 100;
    private static final int EIGHTZEROZERO = 800;
    EventRunner runner = EventRunner.current();
    private String tag = "banner1";
    private HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0, tag);
    private int mLayoutResId = ResourceTable.Layout_banner;
    private Context context;
    private DisplayManager dm;
    private List<String> titles;
    private List imageUrls;
    private List<Component> imageViews;
    private int delayTime = BannerConfig.TIME;
    private int scrollTime = BannerConfig.DURATION;
    private boolean isAutoPlay = BannerConfig.IS_AUTO_PLAY;
    private int titleHeight;
    private int titleBackground;
    private int titleTextColor;
    private int titleTextSize;
    private int bannerBackgroundImage;
    private Image bannerDefaultImage;
    private BannerViewPager viewPager;
    private DirectionalLayout titleView;
    private Text bannerTitle;
    private Text numIndicatorInside;
    private Text numIndicator;
    private BannerScroller mScroller;
    private PageSlider.PageChangedListener mOnPageChangeListener;
    private int count = 0;
    private int currentItem;
    private int bannerStyle = BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE;
    private int scaleType = THREE;
    private int startIndex;
    private BannerPagerAdapter adapter;
    private OnBannerClickListener bannerListener;
    private OnBannerListener listener;
    private int gravity = ONE;
    private boolean isScroll = BannerConfig.IS_SCROLL;
    private WeakHandler handler = new WeakHandler(runner);
    private ImageLoaderInterface imageLoader;
    private IndicatorComponent indicator1;
    private IndicatorComponent indCenter;
    private int orientation = Options.Orientation.INDICATOR_HORIZONTAL;
    private float normalWidthS; // 缩放
    private float checkedWidthS; // 缩放
    private float normalWidth;
    private float checkedWidth;
    private int tagPage = 0;
    private DrawableIndicator drawableIndicator;
    private FigureIndicatorComponent figure;
    private Component dir1;
    private Component dir2;

    /**
     * task
     */
    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            int cut = tagPage + 1; // 下一个轮播页面
            if (cut >= count) {
                cut = 0; // 如果超过长度,则回到起始点
            }
            indicator1.setCurrentPage(cut);
            viewPager.setCurrentPage(cut);
            handler.postDelayed(task, delayTime);
        }
    };

    /**
     * Banner
     *
     * @param context 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public Banner1(Context context) throws NotExistException, WrongTypeException, IOException {
        this(context, null);
    }

    /**
     * Banner
     *
     * @param context 参数
     * @param attrSet 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public Banner1(Context context, AttrSet attrSet) throws NotExistException, WrongTypeException, IOException {
        this(context, attrSet, null);
    }

    /**
     * Banner
     *
     * @param context 参数
     * @param attrSet 参数
     * @param styleName 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public Banner1(Context context, AttrSet attrSet, String styleName)
        throws NotExistException, WrongTypeException, IOException {
        super(context, attrSet, styleName);
        this.context = context;
        titles = new ArrayList<>();
        imageUrls = new ArrayList<>();
        imageViews = new ArrayList<>();
        dm = DisplayManager.getInstance();
        initView(context, attrSet);
    }

    private void initView(Context context1, AttrSet attrs) throws NotExistException, WrongTypeException, IOException {
        imageViews.clear();
        handleTypedArray(context1, attrs);
        Component component = LayoutScatter.getInstance(context1).parse(mLayoutResId, this, true);

        bannerDefaultImage = (Image) component.findComponentById(ResourceTable.Id_bannerDefaultImage);
        viewPager = (BannerViewPager) component.findComponentById(ResourceTable.Id_bannerViewPager);
        titleView = (DirectionalLayout) component.findComponentById(ResourceTable.Id_titleView);
        bannerTitle = (Text) component.findComponentById(ResourceTable.Id_bannerTitle);
        numIndicator = (Text) component.findComponentById(ResourceTable.Id_numIndicator);
        numIndicatorInside = (Text) component.findComponentById(ResourceTable.Id_numIndicatorInside);
        bannerDefaultImage.setImageAndDecodeBounds(bannerBackgroundImage);
        ((ComponentContainer) viewPager.getComponentParent()).setClipEnabled(false);

        normalWidthS = AttrHelper.vp2px(EIGHT, getContext());
        checkedWidthS = normalWidthS * ONEFOUR;

        normalWidth = AttrHelper.vp2px(TEN, getContext());
        checkedWidth = AttrHelper.vp2px(TEN, getContext());
        indicator1 = (IndicatorComponent) findComponentById(ResourceTable.Id_ind);
        indCenter = (IndicatorComponent) findComponentById(ResourceTable.Id_indCenter);
        dir1 = findComponentById(ResourceTable.Id_dir1);
        dir2 = findComponentById(ResourceTable.Id_dir2);
        initViewPagerScroll();
    }

    /**
     * handleTypedArray
     *
     * @param context1 参数
     * @param attrs 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    private void handleTypedArray(Context context1, AttrSet attrs)
        throws NotExistException, WrongTypeException, IOException {
        ResourceManager r1 = context.getResourceManager();
        delayTime = BannerConfig.TIME;
        scrollTime = BannerConfig.DURATION;
        isAutoPlay = BannerConfig.IS_AUTO_PLAY;
        titleBackground = BannerConfig.TITLE_BACKGROUND;
        titleHeight = BannerConfig.TITLE_HEIGHT;
        titleTextColor = BannerConfig.TITLE_TEXT_COLOR;
        titleTextSize = BannerConfig.TITLE_TEXT_SIZE;
        mLayoutResId = mLayoutResId;
        bannerBackgroundImage = ResourceTable.Media_no_banner;
    }

    private void initViewPagerScroll() {
        try {
            Field mField = PageSlider.class.getDeclaredField("mScroller");
            mField.setAccessible(true);
            mScroller = new BannerScroller(viewPager.getContext());
            mScroller.setDuration(scrollTime);
            mField.set(viewPager, mScroller);
        } catch (NoSuchFieldException e) {
            Log.debug(e.getMessage());
        } catch (IllegalAccessException e) {
            Log.debug(e.getMessage());
        }
    }

    @Override
    public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageSliding(toRealPosition(position), positionOffset, positionOffsetPixels);
        }
    }

    /**
     * 返回真实的位置
     *
     * @param position 参数
     * @return 下标从0开始
     */
    public int toRealPosition(int position) {
        int realPosition = 0;
        if (count != 0) {
            realPosition = (position - 1) % count;
        }
        if (realPosition < 0) {
            realPosition += count;
        }
        return realPosition;
    }

    @Override
    public void onPageSlideStateChanged(int state) {
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageSlideStateChanged(state);
        }
        switch (state) {
            case 0:
                if (currentItem == 0) {
                    viewPager.setCurrentPage(count);
                } else if (currentItem == count + 1) {
                    viewPager.setCurrentPage(1);
                }
                break;
            case 1:
                if (currentItem == count + 1) {
                    viewPager.setCurrentPage(1);
                } else if (currentItem == 0) {
                    viewPager.setCurrentPage(count);
                }
                break;
            case TWO:
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageChosen(int position) {
        currentItem = position;
        tagPage = position;
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageChosen(toRealPosition(position));
        }
        if (bannerStyle == BannerConfig.CIRCLE_INDICATOR
            || bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE
            || bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE) {
            Log.debug("1111");
        }
        int posi = position;
        if (position == 0) {
            posi = count;
        }
        if (position > count) {
            posi = 1;
        }
        switch (bannerStyle) {
            case BannerConfig.CIRCLE_INDICATOR:
                break;
            case BannerConfig.NUM_INDICATOR:
                if (indicator1.getVisibility() != TWO) {
                    indicator1.setVisibility(HIDE);
                }
                if (position == count) {
                    posi = 0;
                }
                numIndicator.setText((posi + 1) + "/" + count);
                break;
            case BannerConfig.NUM_INDICATOR_TITLE:
                numIndicatorInside.setText(posi + "/" + count);
                bannerTitle.setText(titles.get(posi - 1));
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE:
                bannerTitle.setText(titles.get(posi - 1));
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE:
                if (position == count) {
                    posi = 0;
                }
                if(position < titles.size()) {
                    bannerTitle.setText(titles.get(position));
                }
                break;
            default:
                break;
        }
    }

    /**
     * setBannerNumStyle
     *
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void setBannerNumStyle() throws NotExistException, WrongTypeException, IOException {
        titleView.setVisibility(HIDE);
        numIndicator.setVisibility(HIDE);
        numIndicatorInside.setVisibility(HIDE);
        this.bannerStyle = bannerStyle;
        start();
    }

    /**
     * start
     *
     * @return this
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public Banner1 start() throws NotExistException, WrongTypeException, IOException {
        numIndicator.setVisibility(HIDE);
        numIndicatorInside.setVisibility(HIDE);
        setBannerStyleUi();
        setImageList(imageUrls);
        setData();
        setIndicatorInside();
        return this;
    }

    /**
     * start1
     *
     * @param y1 参数
     * @return this
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public Banner1 start1(int y1) throws NotExistException, WrongTypeException, IOException {
        setBannerNumStyle();
        setBannerStyleUi();
        setImageList(imageUrls);
        setData();
        if (y1 == 1) {
            setIndicatorInside();
        } else if (TWO == y1) {
            setIndicatorInsideRound();
        } else if (THREE == y1) {
            setIndicatorInsideCenter();
        } else if (FOUR == y1) {
            setIndicatorInsideBelow();
        }
        return this;
    }

    /**
     * setBannerStyleUi
     */
    private void setBannerStyleUi() {
        int visibility = count > 1 ? VISIBLE : HIDE;
        switch (bannerStyle) {
            case BannerConfig.CIRCLE_INDICATOR:
                indicator1.setVisibility(visibility);
                break;
            case BannerConfig.NUM_INDICATOR:
                numIndicator.setVisibility(visibility);
                break;
            case BannerConfig.NUM_INDICATOR_TITLE:
                numIndicatorInside.setVisibility(visibility);
                setTitleStyleUi();
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE:
                setTitleStyleUi();
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE:
                setTitleStyleUi();
                break;
            default:
                break;
        }
    }

    /**
     * setImageList
     *
     * @param imagesUrl1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    private void setImageList(List<?> imagesUrl1) throws NotExistException, WrongTypeException, IOException {
        if (imagesUrl1 == null || imagesUrl1.size() <= 0) {
            bannerDefaultImage.setVisibility(VISIBLE);
            HiLog.error(logLabel, "The image data set is empty.");
            return;
        }
        bannerDefaultImage.setVisibility(HIDE);
        initImages();
        for (int i1 = 0; i1 < count; i1++) {
            Object url = null;
            if (i1 == 0) {
                url = imagesUrl1.get(count - 1);
            } else if (i1 == count + 1) {
                url = imagesUrl1.get(0);
            } else {
                url = imagesUrl1.get(i1 - 1);
            }
            Image image1 = new Image(context);
            setScaleType(image1);
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/jpg";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            ResourceManager manager = context.getResourceManager();
            String path = manager.getMediaPath((Integer) url);
            Resource r1 = manager.getRawFileEntry(path).openRawFile();
            ImageSource source = ImageSource.create(r1, options);
            PixelMap p1 = source.createPixelmap(decodingOptions);
            image1.setPixelMap(p1);
            image1.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                MATCH_PARENT,
                MATCH_PARENT,
                LayoutAlignment.CENTER, ZEROFIVE));
            imageViews.add(image1);
        }
    }

    private void initImages() {
        imageViews.clear();
        if (bannerStyle == BannerConfig.CIRCLE_INDICATOR
            || bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE
            || bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE) {
            Log.debug("1111");
        } else if (bannerStyle == BannerConfig.NUM_INDICATOR_TITLE) {
            numIndicatorInside.setText("1/" + count);
        } else if (bannerStyle == BannerConfig.NUM_INDICATOR) {
            numIndicator.setText("1/" + count);
        }
    }

    /**
     * setTitleStyleUI
     */
    private void setTitleStyleUi() {
        if (titles.size() != imageUrls.size()) {
            Log.debug(titles.size());
        }
        if (titleBackground != ONE) {
            titleView.setBackground(new ElementScatter(context).parse(titleBackground));
        }
        if (titleHeight != ONE) {
            titleView.setLayoutConfig(new DependentLayout.LayoutConfig(MATCH_PARENT, titleHeight));
        }
        if (titleTextColor != ONE) {
            bannerTitle.setTextColor(new Color(titleTextColor));
        }
        if (titleTextSize != ONE) {
            bannerTitle.setTextSize(titleTextSize);
        }
        if (titles != null && titles.size() > 0) {
            bannerTitle.setText(titles.get(0));
            bannerTitle.setVisibility(VISIBLE);
            titleView.setVisibility(VISIBLE);
        }
    }

    private void setData() {
        if (startIndex != 0) {
            currentItem = startIndex;
        } else {
            currentItem = 1;
        }
        if (adapter == null) {
            adapter = new BannerPagerAdapter();
            viewPager.addPageChangedListener(this);
            viewPager.setProvider(adapter);
        } else {
            adapter.notifyDataChanged();
        }
        viewPager.setFocusable(1);
        if (gravity != ONE) {
            if (isScroll && count > 1) {
                viewPager.setScrollable(true);
            } else {
                viewPager.setScrollable(false);
            }
        }
        if (isAutoPlay) {
            startAutoPlay();
        }
        this.setTouchEventListener(new TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                if (isAutoPlay) {
                    int action = touchEvent.getAction();
                    if (action == PRIMARY_POINT_UP || action == CANCEL
                        || action == NONE) {
                        startAutoPlay();
                    } else if (action == PRIMARY_POINT_DOWN) {
                        stopAutoPlay();
                    }
                }
                return true;
            }
        });
    }

    /**
     * startAutoPlay
     */
    public void startAutoPlay() {
        indicator1.isLoop(true);
        handler.removeCallbacks(task);
        handler.postDelayed(task, delayTime);
    }

    /**
     * stopAutoPlay
     */
    public void stopAutoPlay() {
        indicator1.isLoop(false);
        handler.removeCallbacks(task);
    }

    /**
     * BannerPagerAdapter
     *
     * @since 2021-03-24
     */
    class BannerPagerAdapter extends PageSliderProvider {
        @Override
        public int getCount() {
            return imageViews.size();
        }

        /**
         * createPageInContainer
         *
         * @param container 参数
         * @param position 参数
         * @return Object
         */
        @Override
        public Object createPageInContainer(ComponentContainer container, final int position) {
            container.addComponent(imageViews.get(position));
            Component view = imageViews.get(position);
            if (bannerListener != null) {
                view.setClickedListener(v1 -> {
                    HiLogLabel logLabel1 = new HiLogLabel(HiLog.ERROR, 0, tag);
                    HiLog.error(logLabel1, "你正在使用旧版点击事件接口，下标是从1开始，"
                        + "为了体验请更换为setOnBannerListener，下标从0开始计算");
                    bannerListener.onBannerClick(position);
                });
            }
            if (listener != null) {
                view.setClickedListener(new ClickedListener() {
                    @Override
                    public void onClick(Component v1) {
                        listener.onBannerClick(toRealPosition(position));
                    }
                });
            }
            return view;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int i1, Object object) {
            componentContainer.removeComponent((Component) object);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object object) {
            return component == object;
        }
    }

    /**
     * setOnBannerClickListener
     *
     * @param listener1 参数
     * @return this
     */
    @Deprecated
    public Banner1 setOnBannerClickListener(OnBannerClickListener listener1) {
        this.bannerListener = listener1;
        return this;
    }

    /**
     * 废弃了旧版接口，新版的接口下标是从1开始，同时解决下标越界问题
     *
     * @param listener1 参数
     * @return this
     */
    public Banner1 setOnBannerListener(OnBannerListener listener1) {
        this.listener = listener1;
        return this;
    }

    /**
     * isAutoPlay
     *
     * @param isAutoPlay1 参数
     * @return this
     */
    public Banner1 isAutoPlay(boolean isAutoPlay1) {
        this.isAutoPlay = isAutoPlay1;
        return this;
    }

    /**
     * setImageLoader
     *
     * @param imageLoader 参数
     * @return this
     */
    public Banner1 setImageLoader(ImageLoaderInterface imageLoader) {
        this.imageLoader = imageLoader;
        return this;
    }

    /**
     * setBannerBackgroundImage
     *
     * @param attr 参数
     * @return this
     */
    public Banner1 setBannerBackgroundImage(int attr) {
        this.bannerBackgroundImage = attr;
        return this;
    }

    /**
     * setDelayTime
     *
     * @param delayTime 参数
     * @return this
     */
    public Banner1 setDelayTime(int delayTime) {
        this.delayTime = delayTime;
        return this;
    }

    /**
     * setTitleHeight
     *
     * @param attr 参数
     * @return this
     */
    public Banner1 setTitleHeight(int attr) {
        this.titleHeight = attr;
        return this;
    }

    /**
     * setTitleTextColor
     *
     * @param attr 参数
     * @return this
     */
    public Banner1 setTitleTextColor(int attr) {
        this.titleTextColor = attr;
        return this;
    }

    /**
     * setTitleTextSize
     *
     * @param attr1 参数
     * @return this
     */
    public Banner1 setTitleTextSize(int attr1) {
        this.titleTextSize = attr1;
        return this;
    }

    /**
     * setTitleBackground
     *
     * @param attr1 参数
     * @return this
     */
    public Banner1 setTitleBackground(int attr1) {
        this.titleBackground = attr1;
        return this;
    }

    /**
     * setScaleType
     *
     * @param scale 参数
     * @return this
     */
    public Banner1 setScaleType(int scale) {
        scaleType = scale;
        return this;
    }

    /**
     * setScaleType
     *
     * @param imageView 参数
     */
    private void setScaleType(Component imageView) {
        if (imageView instanceof Image) {
            Image view = (Image) imageView;
            switch (scaleType) {
                case 0:
                    view.setScaleMode(Image.ScaleMode.CENTER);
                    break;
                case 1:
                    view.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                    break;
                case TWO:
                    view.setScaleMode(Image.ScaleMode.INSIDE);
                    break;
                case THREE:
                    view.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
                    break;
                case FOUR:
                    view.setScaleMode(Image.ScaleMode.ZOOM_END);
                    break;
                case FIVE:
                    view.setScaleMode(Image.ScaleMode.ZOOM_START);
                    break;
                case SIX:
                    view.setScaleMode(Image.ScaleMode.ZOOM_CENTER);
                    break;
                case SEVEN:
                    view.setScaleMode(Image.ScaleMode.STRETCH);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * setIndicatorGravity
     *
     * @param type 参数
     * @return this
     */
    public Banner1 setIndicatorGravity(int type) {
        switch (type) {
            case BannerConfig.LEFT:
                this.gravity = LayoutAlignment.LEFT | LayoutAlignment.VERTICAL_CENTER;
                break;
            case BannerConfig.CENTER:
                this.gravity = LayoutAlignment.CENTER;
                break;
            case BannerConfig.RIGHT:
                this.gravity = LayoutAlignment.RIGHT | LayoutAlignment.VERTICAL_CENTER;
                break;
            default:
                break;
        }
        return this;
    }

    /**
     * setBannerTitles
     *
     * @param titles1 参数
     * @return this
     */
    public Banner1 setBannerTitles(List<String> titles1) {
        this.titles = titles1;
        return this;
    }

    /**
     * setBannerStyle
     *
     * @param bannerStyle 参数
     * @return this
     */
    public Banner1 setBannerStyle(int bannerStyle) {
        this.bannerStyle = bannerStyle;
        return this;
    }

    /**
     * setViewPagerIsScroll
     *
     * @param isScroll1 参数
     * @return this
     */
    public Banner1 setViewPagerIsScroll(boolean isScroll1) {
        this.isScroll = isScroll1;
        return this;
    }

    /**
     * setImages
     *
     * @param imageUrls1 参数
     * @return this
     */
    public Banner1 setImages(List<?> imageUrls1) {
        this.imageUrls.addAll(imageUrls1);
        this.count = this.imageUrls.size();
        return this;
    }

    /**
     * update
     *
     * @param imageUrls1 参数
     * @param titles1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void update(List<?> imageUrls1, List<String> titles1)
        throws NotExistException, WrongTypeException, IOException {
        this.titles.clear();
        this.titles.addAll(titles1);
        update(imageUrls1);
    }

    /**
     * update
     *
     * @param imageUrls1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void update(List<?> imageUrls1) throws NotExistException, WrongTypeException, IOException {
        this.imageUrls.clear();
        this.imageViews.clear();
        this.imageUrls.addAll(imageUrls1);
        this.count = this.imageUrls.size();
        start();
    }

    /**
     * updateBannerStyle
     *
     * @param bannerStyle1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void updateBannerStyle(int bannerStyle1) throws NotExistException, WrongTypeException, IOException {
        indicator1.setVisibility(HIDE);
        numIndicator.setVisibility(HIDE);
        numIndicatorInside.setVisibility(HIDE);
        bannerTitle.setVisibility(HIDE);
        titleView.setVisibility(HIDE);
        this.bannerStyle = bannerStyle1;
        start();
    }

    /**
     * addUpdate
     *
     * @param imageUrls1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void addUpdate(List<?> imageUrls1) throws NotExistException, WrongTypeException, IOException {
        this.imageUrls.addAll(imageUrls1);
        this.count = this.imageUrls.size();
        if (this.imageUrls.size() >= NINE) {
            return;
        }
        start();
    }

    /**
     * deleteUpdate
     *
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void deleteUpdate() throws NotExistException, WrongTypeException, IOException {
        if (this.imageUrls.size() <= 1) {
            return;
        }
        this.imageUrls.remove(imageUrls.size() - 1);
        this.count = this.imageUrls.size();
        start();
    }

    /**
     * 基本指示器配置(右边)
     */
    public void setIndicatorInside() {
        dir1.setVisibility(HIDE); // 基本指示器配置(右边)
        dir2.setVisibility(HIDE);
        indicator1.setVisibility(VISIBLE);
        indicator1.setSlideMode(Options.IndicatorMode.WORM);
        indicator1.setIndicatorStyle(Options.IndicatorStyle.CIRCLE);
        indicator1.setSliderHeight(AttrHelper.vp2px(SIX, getContext()));
        indicator1.setSliderGap(AttrHelper.vp2px(EIGHT, getContext()));
        indicator1.setOrientation(Options.Orientation.INDICATOR_HORIZONTAL);
        indicator1.setSliderWidth(normalWidth, checkedWidth);
        indicator1.setupWithPageSlide(viewPager);
    }

    /**
     * 基本指示器配置(放在page中间)
     */
    public void setIndicatorInsideCenter() {
        dir1.setVisibility(HIDE);
        dir2.setVisibility(HIDE);
        indicator1.setVisibility(VISIBLE);
        StackLayout.LayoutConfig layoutConfig = (StackLayout.LayoutConfig) indicator1.getLayoutConfig();
        layoutConfig.setMarginBottom(AttrHelper.vp2px(TEN, context));
        layoutConfig.setMarginLeft(AttrHelper.vp2px(THREEZERO, getContext()));
        layoutConfig.alignment = EIGHTONE;
        indicator1.setLayoutConfig(layoutConfig);
        indicator1.setSlideMode(Options.IndicatorMode.WORM);
        indicator1.setIndicatorStyle(Options.IndicatorStyle.CIRCLE);
        indicator1.setSliderHeight(AttrHelper.vp2px(SIX, getContext()));
        indicator1.setSliderGap(AttrHelper.vp2px(EIGHT, getContext()));
        indicator1.setOrientation(Options.Orientation.INDICATOR_HORIZONTAL);
        indicator1.setSliderWidth(normalWidth, checkedWidth);
        indicator1.setupWithPageSlide(viewPager);
    }

    /**
     * 基本指示器配置(放在page下边)
     */
    public void setIndicatorInsideBelow() {
        dir1.setVisibility(HIDE);
        dir2.setVisibility(HIDE);
        indicator1.setVisibility(HIDE);
        indCenter.setVisibility(VISIBLE);
        StackLayout.LayoutConfig layoutConfig = (StackLayout.LayoutConfig) indicator1.getLayoutConfig();
        layoutConfig.setMarginBottom(AttrHelper.vp2px(TEN, context));
        layoutConfig.setMarginLeft(AttrHelper.vp2px(THREEZERO, getContext()));
        layoutConfig.alignment = EIGHTONE;
        indCenter.setLayoutConfig(layoutConfig);
        indCenter.setSlideMode(Options.IndicatorMode.WORM);
        indCenter.setIndicatorStyle(Options.IndicatorStyle.CIRCLE);
        indCenter.setSliderHeight(AttrHelper.vp2px(SIX, getContext()));
        indCenter.setSliderGap(AttrHelper.vp2px(EIGHT, getContext()));
        indCenter.setOrientation(Options.Orientation.INDICATOR_HORIZONTAL);
        indCenter.setSliderWidth(normalWidth, checkedWidth);
        indCenter.setupWithPageSlide(viewPager);
    }

    /**
     * 基本指示器配置（长条）
     */
    public void setIndicatorInsideRound() {
        dir1.setVisibility(HIDE);
        dir2.setVisibility(HIDE);
        indicator1.setVisibility(VISIBLE);
        indicator1.setSlideMode(Options.IndicatorMode.WORM);
        indicator1.setIndicatorStyle(Options.IndicatorStyle.ROUND_RECT);
        indicator1.setSliderHeight(AttrHelper.vp2px(SIX, getContext()));
        indicator1.setSliderGap(AttrHelper.vp2px(EIGHT, getContext()));
        indicator1.setOrientation(Options.Orientation.INDICATOR_HORIZONTAL);
        indicator1.setSliderWidth(normalWidth, checkedWidth);
        indicator1.setupWithPageSlide(viewPager);
    }

    /**
     * 图片指示器配置
     */
    public void setIndicatorInsideDrawable() {
        if(drawableIndicator == null) {
            drawableIndicator = (DrawableIndicator) findComponentById(ResourceTable.Id_drawable_indicator);
        }
        drawableIndicator.setSliderGap(AttrHelper.vp2px(EIGHT, getContext()));
        drawableIndicator.setNormalImageSize(new DrawableIndicator.ImageSize(FIVETY, FIVETY));
        drawableIndicator.setCheckedImageSize(new DrawableIndicator.ImageSize(FIVETY, FIVETY));
        drawableIndicator.setOrientation(Options.Orientation.INDICATOR_HORIZONTAL);
        drawableIndicator.setMediaResId(ResourceTable.Media_heart_empty, ResourceTable.Media_heart_red);
        drawableIndicator.setupWithPageSlide(viewPager);
        StackLayout.LayoutConfig layoutConfig = (StackLayout.LayoutConfig) drawableIndicator.getLayoutConfig();
        layoutConfig.setMarginBottom(AttrHelper.vp2px(TEN, context));
        layoutConfig.height = AttrHelper.vp2px(30,context);
        layoutConfig.alignment =LayoutAlignment.HORIZONTAL_CENTER;
        drawableIndicator.setLayoutConfig(layoutConfig);
        dir1.setVisibility(VISIBLE);
        dir2.setVisibility(HIDE);
        indicator1.setVisibility(HIDE);
        indCenter.setVisibility(HIDE);
        jumpFirst();
    }

    /**
     * setCurrentWidth
     *
     * @param layoutConfig 參數
     * @param Flag 參數
     * @param addItem 參數
     * @return StackLayout.LayoutConfig
     */
    public StackLayout.LayoutConfig setCurrentWidth(StackLayout.LayoutConfig layoutConfig,boolean Flag,int addItem){
        layoutConfig.setMarginBottom(AttrHelper.vp2px(TEN, context));
        if(Flag) {
            if(addItem==3) {
                layoutConfig.width = layoutConfig.width + 219;
            }else{
                layoutConfig.width = layoutConfig.width + 73;
            }
        }else{
            if (this.imageUrls.size() == 3 ||this.imageUrls.size() == 4) {
                layoutConfig.width = layoutConfig.width - 68;
            } else {
                layoutConfig.width = layoutConfig.width - 73;
            }
        }
        layoutConfig.height = AttrHelper.vp2px(30,context);
        layoutConfig.alignment =LayoutAlignment.HORIZONTAL_CENTER;
        return layoutConfig;
    }
    /**
     * 圆形文字指示器配置
     */
    public void setIndictorFigure() {
        dir1.setVisibility(HIDE);
        dir2.setVisibility(VISIBLE);
        indicator1.setVisibility(HIDE);
        indCenter.setVisibility(HIDE);
        figure = (FigureIndicatorComponent) findComponentById(ResourceTable.Id_figure);
        figure.setRadius(AttrHelper.vp2px(TWOTY, getContext()));
        figure.setTextSize(AttrHelper.fp2px(SIXTEEN, getContext()));
        figure.setBackgroundColor(new Color(Color.getIntColor("#aa118EEA")));
        figure.setTextColor(new Color(Color.getIntColor("#ffffff")));
        figure.setupWithPageSlide(viewPager);
        jumpFirst();
    }

    /**
     * 点的形状选择
     *
     * @param i1 参数
     */
    public void setIndicatorStyle(int i1) {
        switch (i1) {
            case 0:
                indicator1.setIndicatorStyle(Options.IndicatorStyle.CIRCLE);
                break;
            case 1:
                indicator1.setIndicatorStyle(Options.IndicatorStyle.DASH);
                break;
            case TWO:
                indicator1.setIndicatorStyle(Options.IndicatorStyle.ROUND_RECT);
                break;
            default:
                break;
        }
        applyIndicator();
    }

    /**
     * 点的移动动画选择
     *
     * @param i1 参数
     */
    public void setSlideMode(int i1) {
        switch (i1) {
            case 0:
                indicator1.setSlideMode(Options.IndicatorMode.SMOOTH);
                break;
            case 1:
                indicator1.setSlideMode(Options.IndicatorMode.WORM);
                break;
            case TWO:
                indicator1.setSlideMode(Options.IndicatorMode.COLOR);
                break;
            case THREE:
                indicator1.setSlideMode(Options.IndicatorMode.SCALE);
                break;
            case FOUR:
                indicator1.setSlideMode(Options.IndicatorMode.NORMAL);
                break;
            default:
                break;
        }
        applyIndicator();
    }

    /**
     * 指示器的选择与未选宽
     */
    private void applyIndicator() {
        if (indicator1.getSlideMode() == Options.IndicatorMode.SCALE) {
            indicator1.setSliderWidth(normalWidthS, checkedWidthS);
        } else {
            indicator1.setSliderWidth(normalWidth, checkedWidth);
        }
        indicator1.notifyDataChanged();
    }

    /**
     * 重新跳转到第一个
     */
    public void jumpFirst() {
        indicator1.setCurrentPage(0);
        if (drawableIndicator != null) {
            drawableIndicator.setCurrentPage(0);
        }
        if (figure != null) {
            figure.setCurrentPage(0);
        }
        viewPager.setCurrentPage(0);
    }

    /**
     * 随机跳转
     *
     * @return t1跳转页数
     */
    public int jumpRadom() {
        int t1 = (int) (Math.random() * ONEZEROZERO) % this.imageUrls.size();
        indicator1.setCurrentPage(t1);
        if (drawableIndicator != null) {
            drawableIndicator.setCurrentPage(t1);
        }
        if (figure != null) {
            figure.setCurrentPage(t1);
        }
        viewPager.setCurrentPage(t1);
        return t1;
    }

    /**
     * 增加三张图片
     *
     * @param imageUrls1 新增图片
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void addThreeImage(List<?> imageUrls1) throws NotExistException, WrongTypeException, IOException {
        setImageListImage(imageUrls1);
        this.imageUrls.addAll(imageUrls1);
        this.count = this.imageUrls.size();
        viewPager.getProvider().notifyDataChanged();
        indCenter.setPageSize(this.imageUrls.size());
        indCenter.notifyDataChanged();
        if (drawableIndicator != null) {
            drawableIndicator.setPageSize(this.imageUrls.size());
            drawableIndicator.notifyDataChanged();
            if(imageUrls1.size() == 3) {
                drawableIndicator.setLayoutConfig(setCurrentWidth((StackLayout.LayoutConfig) drawableIndicator.getLayoutConfig(), true,3));
            }else{
                drawableIndicator.setLayoutConfig(setCurrentWidth((StackLayout.LayoutConfig) drawableIndicator.getLayoutConfig(), true,1));
            }
        }
        if (figure != null) {
            figure.setPageSize(this.imageUrls.size());
            figure.notifyDataChanged();
        }
    }

    /**
     * 删减一张图片
     *
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public void deleteUpdateImage() throws NotExistException, WrongTypeException, IOException {
        if (this.imageUrls.size() <= 1) {
            return;
        }
        this.imageUrls.remove(imageUrls.size() - 1);
        this.imageViews.remove(imageViews.size() - 1);
        this.count = this.imageUrls.size();
        viewPager.getProvider().notifyDataChanged();
        indCenter.setPageSize(this.imageUrls.size());
        indCenter.notifyDataChanged();
        if (drawableIndicator != null) {
            drawableIndicator.setPageSize(this.imageUrls.size());
            drawableIndicator.notifyDataChanged();
            drawableIndicator.setLayoutConfig(setCurrentWidth((StackLayout.LayoutConfig)drawableIndicator.getLayoutConfig(),false,0));
        }
        if (figure != null) {
            figure.setPageSize(this.imageUrls.size());
            figure.notifyDataChanged();
        }
    }

    /**
     * 更改imageView 的长度
     *
     * @param imagesUrl1 参数
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    private void setImageListImage(List<?> imagesUrl1) throws NotExistException, WrongTypeException, IOException {
        if (imagesUrl1 == null || imagesUrl1.size() <= 0) {
            bannerDefaultImage.setVisibility(VISIBLE);
            HiLog.error(logLabel, "The image data set is empty.");
            return;
        }
        bannerDefaultImage.setVisibility(HIDE);
        for (int i1 = 0; i1 < imagesUrl1.size(); i1++) {
            Object url = null;
            url = imagesUrl1.get(i1);
            Image image1 = new Image(context);
            setScaleType(image1);
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/jpg";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            ResourceManager manager = context.getResourceManager();
            String path = manager.getMediaPath((Integer) url);
            Resource r1 = manager.getRawFileEntry(path).openRawFile();
            ImageSource source = ImageSource.create(r1, options);
            PixelMap p1 = source.createPixelmap(decodingOptions);
            image1.setPixelMap(p1);
            image1.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                MATCH_PARENT, MATCH_PARENT, LayoutAlignment.CENTER, ZEROFIVE));
            this.imageViews.add(image1);
        }
    }

    /**
     * getIamgeNum
     *
     * @return int
     */
    public int getIamgeNum() {
        return this.imageUrls.size();
    }
}
